'''
Author: duliang thinktanker@163.com
Date: 2025-08-01 23:41:35
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-08-23 11:48:32
FilePath: 
Description:小程序推送订阅信息
'''
import requests
import json
import time
import sqlite3
from fapiao import getRealnameByopenid

class WechatAPI:
    def __init__(self, app_id, app_secret):
        self.app_id = app_id
        self.app_secret = app_secret
        self.access_token = None
        self.token_expires = 0

    def get_access_token(self):
        """获取微信接口调用凭证"""
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.app_id}&secret={self.app_secret}"
        response = requests.get(url)
        data = response.json()
        if 'access_token' in data:
            self.access_token = data['access_token']
            self.token_expires = data.get('expires_in', 7200) + int(
                time.time())
            return self.access_token
        else:
            raise Exception(f"获取access_token失败: {data}")

    def send_subscribe_message(self, openid, template_id, data, page=None):
        """发送订阅消息
        
        :param openid: 接收者openid
        :param template_id: 订阅消息模板ID
        :param data: 消息内容，格式参考微信文档
        :param page: 点击消息跳转的小程序页面
        :return: 发送结果
        """
        if not self.access_token or time.time() > self.token_expires:
            self.get_access_token()

        url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={self.access_token}"

        payload = {"touser": openid, "template_id": template_id, "data": data}
        print(payload)
        if page:
            payload["page"] = page

        headers = {'Content-Type': 'application/json'}

        response = requests.post(
            url,
            data=json.dumps(payload, ensure_ascii=False).encode('utf-8'),
            headers=headers)
        return response.json()


# 配置参数
APP_ID = "wx548ae2a8c8025478"
APP_SECRET = "0a9b9a52efc0a7e26478a57060faca7d"
TEMPLATE_ID = "qskZOdPVPNH8OjS-hHSccZRYR3pWdlKU_8xZSh16Wv8"

# 初始化微信API
wechat = WechatAPI(APP_ID, APP_SECRET)


# 发送订阅消息
def send_notification(openid,
                      template_name,
                      values=(),
                      page="pages/index/index"):
    '''
    告警标题
    {{thing10.DATA}}
    告警时间
    {{time2.DATA}}
    告警地点
    {{thing4.DATA}}
    告警状态
    {{phrase22.DATA}}
    备注
    {{thing3.DATA}}
    '''

    with open("./config/config.json", "r", encoding="utf-8") as f:
        template = json.load(f)
        TEMPLATE_ID = template.get("template_id").get(template_name).get("id")
        data = template.get("template_id").get(template_name).get("data")
        # 为每个值添加"value"键
        template_content = {
            key: {
                "value": value
            }
            for key, value in zip(data, values)
        }
        # 转换为 JSON 格式
        # print(template_content)

    realname = getRealnameByopenid(openid)
    print(realname, openid)
    if not realname:
        realname = "未知"
    try:
        result = wechat.send_subscribe_message(openid=openid,
                                               template_id=TEMPLATE_ID,
                                               data=template_content,
                                               page=page)

        print("消息发送结果:", realname, result)
        return result
    except Exception as e:
        print("消息发送失败:", realname, str(e))
    return None


def get_accepted_templates(subscribe_result):
    """
    从订阅结果中获取用户同意的模板ID列表
    
    :param subscribe_result: wx.requestSubscribeMessage返回的结果
    :return: 用户同意的模板ID列表
    """
    accepted_templates = []

    # 遍历结果字典
    for key, value in subscribe_result.items():
        # 排除errMsg字段，只处理模板ID
        if key != 'errMsg' and value == 'accept':
            accepted_templates.append(key)

    return accepted_templates


def update_user_template_id(openid, res):
    """
    更新用户的模板ID
    """
    if res:
        template_id_list = get_accepted_templates(res)
        if template_id_list:
            conn = sqlite3.connect('./data/users.db')
            cursor = conn.cursor()
            cursor.execute("SELECT template_id  FROM users WHERE openid = ?",
                           (openid, ))
            template_id = cursor.fetchone()
            # for template_id in template_id_list:
            try:
                if template_id:
                    if template_id[0]:
                        template_id = eval(template_id[0])
                        template_id = list(set(template_id + template_id_list))
                    else:
                        template_id = template_id_list
                    cursor.execute(
                        "UPDATE users SET template_id = ? WHERE openid = ?",
                        (str(template_id), openid))
            except Exception as e:
                print(e)
            conn.commit()
            conn.close()
            return True

    return False


# 新增函数: 通过template_id获取对应的key名称
def get_template_name_by_id(template_id):
    """
    通过template_id获取在config.json中对应的key名称
    
    :param template_id: 模板ID
    :return: 对应的key名称，如果未找到则返回None
    """
    try:
        with open("./config/config.json", "r", encoding="utf-8") as f:
            config = json.load(f)
            template_configs = config.get("template_id", {})

            # 遍历所有模板配置，查找匹配的template_id
            for key, value in template_configs.items():
                if isinstance(value, dict) and value.get("id") == template_id:
                    return key
            return None
    except Exception as e:
        print(f"读取配置文件失败: {e}")
        return None


if __name__ == '__main__':
    # 2019-10-22 14:41:11
    # timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    # values = ("测试", timestr)

    # # 示例调用
    # send_notification("审批", ("已审批", timestr, "10000.20", timestr, "通过"))
    from savewarning import get_openids_by_template_id

    # send_notification(
    #     "oPQDE5KA-SXhlayCSSaH6VoB31Pk",
    #     "告警",
    #     (
    #         #时间
    #         time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
    #         # 备注
    #         f"超限30%",
    #         # 地点
    #         f"测试机组",
    #         # 标题
    #         "测试标题",
    #         # 状态
    #         "摆度异常"),
    #     "pages/gongqing/gongqing")
    send_notification("oPQDE5KA-SXhlayCSSaH6VoB31Pk", "招标",
                      ("测试1", "测试2", "2025-08-09 12:00"),
                      "pages/index/index?query=测试标题")
